import { defineStore } from 'pinia'

// 存储用户信息
export const useUserStore = defineStore('user', {
    state: () => ({
        username: '',
        loginTime: '',
        type: '',
        token: ''
    }),
    getters: {
        getUser() {
            // 如果用户名为空并且 sessionStorage 中存在用户数据，则加载 sessionStorage 中的数据
            if (!this.username && sessionStorage.getItem('user')) {
                const user = JSON.parse(sessionStorage.getItem('user'));
                this.username = user.username;
                this.loginTime = user.loginTime;
                this.type = user.type;
                this.token = user.token;
            }
            return {
                username: this.username,
                loginTime: this.loginTime,
                type: this.type,
                token: this.token
            };
        }
    },
    actions: {
        setUser(data) {
            this.username = data.username;
            this.loginTime = data.loginTime;
            this.type = data.type;
            this.token = data.token;
            // 存储到 sessionStorage
            sessionStorage.setItem('user', JSON.stringify({
                username: data.username,
                loginTime: data.loginTime,
                type: data.type,
                token: data.token
            }));
        },
        delUser() {
            // 清除 sessionStorage 中的用户信息
            sessionStorage.removeItem('user');
            this.username = '';
            this.loginTime = '';
            this.type = '';
            this.token = '';

        }
    }
});


export const useAuthStore = defineStore('auth', {
  state: () => ({
    username: "",
    type: 0,
    openId: 0,
    password: "",
      token: ""
  }),
  actions: {
    updateLoginInformation(info) {
      this.username = info.username;
      this.type = info.type;
      this.openId = info.openId;
      this.password = info.password;
      // this.token = info.token;
    }
  }
});


// 存储菜单信息
export const useMenuStore = defineStore('menu', {
    state: () => ({
        menu: '',
    }),
    getters: {
        getMenu(){
            if(!this.menu){
                this.menu = JSON.parse(sessionStorage.getItem('menu'))
            }
            return this.menu;
        }
    },
    actions: {
        setMenu (data) {
            this.menu = data
            sessionStorage.setItem('menu', JSON.stringify(data))
        },
        delMenu () {
            sessionStorage.clear()
        }
    }
})


